package com.elitedatai.mchtest.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Converter(autoApply = false)
public class LongListListConverter implements AttributeConverter<List<List<Long>>, String> {

    private static ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        LongListListConverter.objectMapper = objectMapper;
    }

    @Override
    public String convertToDatabaseColumn(List<List<Long>> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Error converting List<List<Long>> to JSON", e);
        }
    }

    @Override
    public List<List<Long>> convertToEntityAttribute(String dbData) {
        if (dbData == null || dbData.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(dbData, new TypeReference<List<List<Long>>>() {});
        } catch (IOException e) {
            throw new IllegalArgumentException("Error converting JSON to List<List<Long>>", e);
        }
    }
}
